<?php
class CartController extends ServiceController {
	public function serviceGet(){
		$customerId = Yii::app()->user->id;
		$cartInfo = CartProductMap::model()->with('product','product.cover')->findAllByAttributes(array('customerid'=>$customerId));
		$cartArr = array();
		if($cartInfo){
			foreach($cartInfo as $cartItem){
				$cartArr[] = array(
						'id'=>$cartItem->id,
						'name'=>$cartItem->product->name,
						'price'=>$cartItem->amount,
						'num'=>$cartItem->num,
						'total'=>$cartItem->total,
						'image'=>isset($cartItem->product->cover)?$cartItem->product->cover->realUrl:'',
						'unit'=>Utils::getCurrencyUnit($cartItem->currency)
				);
			}
		}
		Utils::ajaxReturn($cartArr);
	}
	
	public function serviceDelete($id){
		$customerId = Yii::app()->user->id;
		$cart = Cart::model()->findByAttributes(array('customerid'=>$customerId));
		if(!empty($cart) && CartProductMap::model()->deleteByPk(array('customerid'=>$customerId,'productid'=>$id,'cartid'=>$cart->id))){
			Utils::ajaxReturn('',true);
		}else{
			Utils::ajaxReturn('',false);
		}
	}
	
	public function serviceCreate($data){
		$customerId = Yii::app()->user->id;
		if(empty($customerId)){
			Utils::ajaxReturn('loginFirst',false,'请先登录');
		}
		$flag = Cart::model()->addProduct($customerId,$data);
		$success = $flag?true:false;
		Utils::ajaxReturn('',$success);
	}
	
	public function serviceUpdate($id,$cart){
		$cartMapModel = CartProductMap::model()->findByPk($id);
		$cartMapModel->num = $cart['num'];
		$cartMapModel->total = $cart['num']*$cart['price'];
		if($cartMapModel->update(array('num','total'))){
			Utils::ajaxReturn('',true);
		}else{
			Utils::ajaxReturn('',false);
		}
	}
	
	public function actionCartNum(){
		$customerId = Yii::app()->user->id;
		$count = CartProductMap::model()->countByAttributes(array('customerid'=>$customerId));
		$count = empty($count)?0:intval($count);
		Utils::ajaxReturn($count);
	}
	
}


?>